package group.sicher.log.aop;

import group.sicher.log.recorder.MethodRecorder;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;


/**
 * @author Donald
 * @description
 * @date 2019-08-05
 **/
@Aspect
public class MethodLogAspect {

    private MethodRecorder recorder;

    @Autowired
    public MethodLogAspect(MethodRecorder recorder) {
        this.recorder = recorder;
    }

    @Around(value = "@annotation(group.sicher.log.aop.annotation.Log) || @annotation(group.sicher.log.aop.annotation.AllLog)")
    public Object aroundMethod(ProceedingJoinPoint joinPoint) throws Throwable {

        long start = System.currentTimeMillis();

        Object result = joinPoint.proceed();

        long cost = System.currentTimeMillis() - start;

        recorder.record(joinPoint, result, cost);

        return result;
    }

    @AfterThrowing(value = "@annotation(group.sicher.log.aop.annotation.ThrowLog) || @annotation(group.sicher.log.aop.annotation.AllLog)", throwing = "e")
    public void afterThrowing(JoinPoint joinPoint, Throwable e) {
        recorder.record(joinPoint, e);
    }
}
